<template>
  <el-card style="width: 100%">
    <template #header>
      <div class="flex-between">
        <span>科室管理</span>
        <el-button type="primary" @click="openDialog">新增科室</el-button>
      </div>
    </template>

    <!-- 查询 -->
    <el-form :inline="true" :model="query" class="mb-3">
      <el-form-item label="关键字">
        <el-input v-model="query.keyword" placeholder="科室编码/名称" clearable />
      </el-form-item>
      <el-button type="primary" @click="onQuery">查询</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form>

    <!-- 列表 -->
    <el-table :data="list" border stripe class="nowrap-table" style="width: 100%">
      <!-- 去掉 ID 列 -->
      <el-table-column prop="deptcode"  label="科室编码"  min-width="120" />
      <el-table-column prop="deptname"  label="科室名称"  min-width="150" />

      <el-table-column label="类别" min-width="120">
        <template #default="{ row }">
          {{ categoryMap[row.deptcategoryid] || row.deptcategoryid }}
        </template>
      </el-table-column>
      <el-table-column label="类型" min-width="120">
        <template #default="{ row }">
          {{ typeMap[row.depttype] || row.depttype }}
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" min-width="180">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="onEdit(row.id)">编辑</el-button>
          <el-button size="small" type="danger"  @click="onDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-4 text-right">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="query.page"
          v-model:page-size="query.pageSize"
          @current-change="onPageChange"
          @size-change="onSizeChange"
      />
    </div>

    <!-- 新增 / 编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="640px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px" status-icon>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="科室编码" prop="deptcode">
              <el-input v-model="form.deptcode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室名称" prop="deptname">
              <el-input v-model="form.deptname" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="类别" prop="deptcategoryid">
              <el-select v-model="form.deptcategoryid" placeholder="请选择类别">
                <el-option v-for="c in categoryOptions" :key="c.id" :label="c.name" :value="c.id"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="类型" prop="depttype">
              <el-select v-model="form.depttype" placeholder="请选择类型">
                <el-option v-for="t in typeOptions" :key="t.id" :label="t.name" :value="t.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

interface DeptItem {
  id?: number
  deptcode: string
  deptname: string
  deptcategoryid: number | ''
  depttype: number | ''
}
interface OptionItem { id:number; name:string }

const list  = ref<DeptItem[]>([])
const total = ref(0)
const query = reactive({ keyword:'', page:1, pageSize:10 })

const categoryOptions = ref<OptionItem[]>([])
const typeOptions     = ref<OptionItem[]>([])
const categoryMap: Record<number,string> = {}
const typeMap:     Record<number,string> = {}

const toArr = (r:any)=>Array.isArray(r)?r:Array.isArray(r.records)?r.records:Array.isArray(r.data)?r.data:[]

async function loadDictionaries(){
  const [catRes, typeRes] = await Promise.all([
    axios.get('/api/master/constant/item/list', { params:{ typeId:1 } }),
    axios.get('/api/master/constant/type/list', { params:{ pageSize:999 } }),
  ])
  categoryOptions.value = toArr(catRes.data).map((i:any)=>({ id:i.id, name:i.constantname }))
  categoryOptions.value.forEach(i=>categoryMap[i.id]=i.name)

  typeOptions.value = toArr(typeRes.data).map((t:any)=>({ id:t.id, name:t.constanttypename }))
  typeOptions.value.forEach(t=>typeMap[t.id]=t.name)
}

async function loadData() {
  const { data } = await axios.get('/api/master/dept', { params: query })
  let rows: DeptItem[]

  if (Array.isArray(data)) {
    rows = data
    total.value = data.length
  } else {
    rows = toArr(data.records ?? data)
    total.value = data.total ?? rows.length
  }

  if (query.keyword) {
    rows = rows.filter(d =>
        d.deptcode.includes(query.keyword) || d.deptname.includes(query.keyword)
    )
  }
  list.value = rows
}

function onQuery(){ query.page=1; loadData() }
function onReset(){ query.keyword=''; onQuery() }
function onPageChange(p:number){ query.page=p; loadData() }
function onSizeChange(s:number){ query.pageSize=s; query.page=1; loadData() }

const dialogVisible = ref(false)
const dialogTitle   = ref('')
const formRef       = ref()
const form = reactive<DeptItem>({ deptcode:'', deptname:'', deptcategoryid:'', depttype:'' })

const rules = {
  deptcode:[{ required:true, message:'请输入编码', trigger:'blur' }],
  deptname:[{ required:true, message:'请输入名称', trigger:'blur' }],
  deptcategoryid:[{ required:true, message:'请选择类别', trigger:'change' }],
  depttype:[{ required:true, message:'请选择类型', trigger:'change' }],
}
function openDialog(){ dialogTitle.value='新增科室'; Object.assign(form,{ id:undefined, deptcode:'', deptname:'', deptcategoryid:'', depttype:'' }); dialogVisible.value=true }
async function onEdit(id?:number){ if(!id) return; const { data } = await axios.get(`/api/master/dept/${id}`); Object.assign(form,data); dialogTitle.value='编辑科室'; dialogVisible.value=true }
async function onSubmit(){ await formRef.value?.validate(); if(form.id){ await axios.put('/api/master/dept',form); ElMessage.success('修改成功') } else { await axios.post('/api/master/dept',form); ElMessage.success('新增成功') } dialogVisible.value=false; loadData() }
function onDelete(id?:number){ if(!id) return; ElMessageBox.confirm('确认删除?','提示',{ type:'warning' }).then(async()=>{ await axios.delete(`/api/master/dept/${id}`); ElMessage.success('删除成功'); loadData() }) }

onMounted(async()=>{ await loadDictionaries(); await loadData() })
</script>

<style scoped>
.flex-between{display:flex;justify-content:space-between;align-items:center}
.mb-3{margin-bottom:12px}
.nowrap-table .cell{white-space:nowrap}
</style>
